package com.unicorn.util.common;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Tool {


	private static Logger logger= LoggerFactory.getLogger(MD5Tool.class);

	static MessageDigest md = null;

	static {
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException ne) {
			logger.info("MD5 Tools");
		}
	}

	public static String getMD5(File file) {

		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			//100KB each time
			byte[] buffer = new byte[102400];
			int length;
			long loopCount = 0;
			while ((length = fis.read(buffer)) != -1) {
				md.update(buffer, 0, length);
				loopCount++;
			}

			logger.debug("read file to buffer loopCount:"+loopCount);

			return new String(Hex.encodeHex(md.digest()));
		} catch (FileNotFoundException e) {
			logger.error("md5 file " + file.getAbsolutePath() + " failed:" + e.getMessage());
			return null;
		} catch (IOException e) {
			logger.error("md5 file " + file.getAbsolutePath() + " failed:" + e.getMessage());
			return null;
		} finally {
			try {
				if (fis != null) fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}


	}

	public final static String MD5(String s){
		char hexDigits[] = {
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
		'e', 'f'};
		try {
		byte[] strTemp = s.getBytes();
		MessageDigest mdTemp = MessageDigest.getInstance("MD5");
		mdTemp.update(strTemp);
		byte[] md = mdTemp.digest();
		int j = md.length;
		char str[] = new char[j * 2];
		int k = 0;
		for (int i = 0; i < j; i++) {
		byte byte0 = md[i];
		str[k++] = hexDigits[byte0 >>> 4 & 0xf];
		str[k++] = hexDigits[byte0 & 0xf];
		}
		return new String(str);
		}
		catch (Exception e){
		return null;
		}
		} 
	
	public static void main(String [] arg)
	{
		String aa = "ab105451";
		
		System.out.println(MD5(aa));
		
	}
	

		
}
